var list1txt = "";
var list2txt = "";

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "menuId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};

toastr.options = {
    "closeButton": true,
    "debug": false,
    "progressBar": true,
    "positionClass": "toast-top-right",
    "onclick": null,
    "showDuration": "400",
    "hideDuration": "1000",
    "timeOut": "3000",
    "extendedTimeOut": "1000",
    "showEasing": "swing",
    "hideEasing": "linear",
    "showMethod": "fadeIn",
    "hideMethod": "fadeOut"
};



var updateOutput = function (e) {
	
    var list = e.length ? e : $(e.target);

    var output = list.data('output');

    console.log(window.JSON.stringify(list.nestable('serialize')));

    if (window.JSON) {
        output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2));
    } else {
        output.val('浏览器不支持');
    }
};

var menu2SortChance = function (e) {
    var list = e.length ? e : $(e.target);
    var output = list.data('output');
    var data = list.nestable('serialize')
    $.ajax({
        type: "POST",
        url: "../sys/menu/sort",
        data: JSON.stringify(data),
        success: function(r){
            if(r.code === 0){
                toastr.success("排序成功");
            }else{
                toastr.error(r.msg);
            }
        }
    });

}

//生成菜单
var menuItem1 = Vue.extend({
    name: 'menu-item',
    props:{item:{}},
    template:[
        '<li class="dd-item  dd-item-alt" :data-id="item.menuId" :data-sort="item.orderNum" >',
        '<div class="dd-handle">',
        '</div>',
        '<div class="dd-content" v-on:click="itemClick(item)">',
        '<span v-if="item.type!=2 && 1==2" class="pull-right"> {{item.orderNum}} </span>',
        '<span class="label label-info"><i v-if="item.icon != null" :class="item.icon"></i></span> {{item.name}}',
        '</div>',
        '</li>'
    ].join(''),
    methods: {
        itemClick: function(item){
            this.$emit('menu-click',item);
        }
    }
});
//生成菜单
var menuItem2 = Vue.extend({
    name: 'menu-item',
    props:{item:{}},
    template:[
        '<li class="dd-item  dd-item-alt" :data-id="item.menuId" :data-sort="item.orderNum" >',
        '<button v-if="item.type!=2 && item.children.length > 0" data-action="collapse" class="pull-right" type="button" style="display:' +
        ' block;">关闭</button>',
        '<button v-if="item.type!=2 && item.children.length > 0" data-action="expand" class="pull-right" type="button" style="display:' +
        ' none;">展开</button>',
        '<div class="dd-handle " v-if="item.type!=2">',
        '</div>',
        '<div class="dd-content" v-on:click="itemClick(item)">',
		'<span v-if="item.type!=2 && 1==2"  class="pull-right"> {{item.orderNum}} </span>',
        '<span class="label label-info" v-if="item.icon != null">' +
        '<i :class="item.icon"></i>' +
        '</span> ' +
        '<span class="label" v-if="item.icon == null">' +
        '<i class="fa fa-square-o"></i>' +
        '</span> ' +
        '{{item.name}}',
        '</div>',
        '<ol v-if="item.children.length > 0" class="dd-list">',
        '<menu-item :item="item" :key="item.menuId" v-on:menu-click="itemClick($event)" v-for="item in item.children"></menu-item>',
        '</ol>',
        '</li>'
    ].join(''),
    methods: {
        itemClick: function(item){
            this.$emit('menu-click',item);
        }
    }
});

//注册菜单组件
Vue.component('menuItem1',menuItem1);
Vue.component('menuItem',menuItem2);


var vm = new Vue({
	el:'#rrapp',
	data:{
        menuList:{},
        menuList2:[],
        menuList3:{},
		showList: true,
        showOpen: false,
        dialogIconVisible:false,
		title: null,
		menu:{
			parentName:null,
			parentId:0,
			type:1,
			orderNum:0
		},
        typeList: [
            {'value': 0, 'text': '目录'},
            {'value': 1, 'text': '菜单'},
            {'value': 2, 'text': '按钮'}
        ],
        statusList: [
            {'value': 1, 'text': '显示'},
            {'value': 0, 'text': '隐藏'}
        ],
        statusMap: {},
        platList:[
            {'id': 1, 'platName': '系统管理台'},
            {'id': 2, 'platName': 'SP门户'}
        ],
        plat:1,
        typeMap: {},
        showView: true,
        addView:false,
        sysMenu:{'status':1},
        sysMenuAdd:{'parentName':''},
        icons:["address-book","address-book-o","address-card","address-card-o","adjust","american-sign-language-interpreting","anchor","archive","area-chart","arrows","arrows-h","arrows-v","asl-interpreting","assistive-listening-systems","asterisk","at","audio-description","automobile","balance-scale","ban","bank","bar-chart","bar-chart-o","barcode","bars","bath","bathtub","battery","battery-0","battery-1","battery-2","battery-3","battery-4","battery-empty","battery-full","battery-half","battery-quarter","battery-three-quarters","bed","beer","bell","bell-o","bell-slash","bell-slash-o","bicycle","binoculars","birthday-cake","blind","bluetooth","bluetooth-b","bolt","bomb","book","bookmark","bookmark-o","braille","briefcase","bug","building","building-o","bullhorn","bullseye","bus","cab","calculator","calendar","calendar-check-o","calendar-minus-o","calendar-o","calendar-plus-o","calendar-times-o","camera","camera-retro","car","caret-square-o-down","caret-square-o-left","caret-square-o-right","caret-square-o-up","cart-arrow-down","cart-plus","cc","certificate","check","check-circle","check-circle-o","check-square","check-square-o","child","circle","circle-o","circle-o-notch","circle-thin","clock-o","clone","close","cloud","cloud-download","cloud-upload","code","code-fork","coffee","cog","cogs","comment","comment-o","commenting","commenting-o","comments","comments-o","compass","copyright","creative-commons","credit-card","credit-card-alt","crop","crosshairs","cube","cubes","cutlery","dashboard","database","deaf","deafness","desktop","diamond","dot-circle-o","download","drivers-license","drivers-license-o","edit","ellipsis-h","ellipsis-v","envelope","envelope-o","envelope-open","envelope-open-o","envelope-square","eraser","exchange","exclamation","exclamation-circle","exclamation-triangle","external-link","external-link-square","eye","eye-slash","eyedropper","fax","feed","female","fighter-jet","file-archive-o","file-audio-o","file-code-o","file-excel-o","file-image-o","file-movie-o","file-pdf-o","file-photo-o","file-picture-o","file-powerpoint-o","file-sound-o","file-video-o","file-word-o","file-zip-o","film","filter","fire","fire-extinguisher","flag","flag-checkered","flag-o","flash","flask","folder","folder-o","folder-open","folder-open-o","frown-o","futbol-o","gamepad","gavel","gear","gears","gift","glass","globe","graduation-cap","group","hand-grab-o","hand-lizard-o","hand-paper-o","hand-peace-o","hand-pointer-o","hand-rock-o","hand-scissors-o","hand-spock-o","hand-stop-o","handshake-o","hard-of-hearing","hashtag","hdd-o","headphones","heart","heart-o","heartbeat","history","home","hotel","hourglass","hourglass-1","hourglass-2","hourglass-3","hourglass-end","hourglass-half","hourglass-o","hourglass-start","i-cursor","id-badge","id-card","id-card-o","image","inbox","industry","info","info-circle","institution","key","keyboard-o","language","laptop","leaf","legal","lemon-o","level-down","level-up","life-bouy","life-buoy","life-ring","life-saver","lightbulb-o","line-chart","location-arrow","lock","low-vision","magic","magnet","mail-forward","mail-reply","mail-reply-all","male","map","map-marker","map-o","map-pin","map-signs","meh-o","microchip","microphone","microphone-slash","minus","minus-circle","minus-square","minus-square-o","mobile","mobile-phone","money","moon-o","mortar-board","motorcycle","mouse-pointer","music","navicon","newspaper-o","object-group","object-ungroup","paint-brush","paper-plane","paper-plane-o","paw","pencil","pencil-square","pencil-square-o","percent","phone","phone-square","photo","picture-o","pie-chart","plane","plug","plus","plus-circle","plus-square","plus-square-o","podcast","power-off","print","puzzle-piece","qrcode","question","question-circle","question-circle-o","quote-left","quote-right","random","recycle","refresh","registered","remove","reorder","reply","reply-all","retweet","road","rocket","rss","rss-square","s15","search","search-minus","search-plus","send","send-o","server","share","share-alt","share-alt-square","share-square","share-square-o","shield","ship","shopping-bag","shopping-basket","shopping-cart","shower","sign-in","sign-language","sign-out","signal","signing","sitemap","sliders","smile-o","snowflake-o","soccer-ball-o","sort","sort-alpha-asc","sort-alpha-desc","sort-amount-asc","sort-amount-desc","sort-asc","sort-desc","sort-down","sort-numeric-asc","sort-numeric-desc","sort-up","space-shuttle","spinner","spoon","square","square-o","star","star-half","star-half-empty","star-half-full","star-half-o","star-o","sticky-note","sticky-note-o","street-view","suitcase","sun-o","support","tablet","tachometer","tag","tags","tasks","taxi","television","terminal","thermometer","thermometer-0","thermometer-1","thermometer-2","thermometer-3","thermometer-4","thermometer-empty","thermometer-full","thermometer-half","thermometer-quarter","thermometer-three-quarters","thumb-tack","thumbs-down","thumbs-o-down","thumbs-o-up","thumbs-up","ticket","times","times-circle","times-circle-o","times-rectangle","times-rectangle-o","tint","toggle-down","toggle-left","toggle-off","toggle-on","toggle-right","toggle-up","trademark","trash","trash-o","tree","trophy","truck","tty","tv","umbrella","universal-access","university","unlock","unlock-alt","unsorted","upload","user","user-circle","user-circle-o","user-o","user-plus","user-secret","user-times","users","vcard","vcard-o","video-camera","volume-control-phone","volume-down","volume-off","volume-up","warning","wheelchair","wheelchair-alt","wifi","window-close","window-close-o","window-maximize","window-minimize","window-restore","wrench"],
        rules: {
            menuId: [
                {required: true, message: '请输入菜单ID', trigger: 'blur'}
            ],
            test:[]
        }
	},
    mounted: function () {
        this.typeMap = list2Map(this.typeList)
        this.statusMap = list2Map(this.statusList)
        this.getMenuList();
        this.menu1Sort();
        this.menu2Sort();

    },
	methods: {
        getMenuList: function () {

            $.getJSON("../sys/menu/list?plat=" + this.plat + "&_"+$.now(), function(r){
                vm.menuList = r.data.menuList;
                if(vm.menuList.length > 0)
				{
				    if(vm.menuList2.length == 0)
                    {
                        vm.menuList2 = vm.menuList[0].children;
                        vm.menuList3 = [vm.menuList[0]]
                        $.get("../sys/menu/info/"+vm.menuList[0].menuId, function(r){
                            vm.sysMenu = r.data;
                            vm.getMenu(vm.sysMenu.menuId);
                        });
                    }

				}
            });
        },
        platChange: function(){
            this.menuList2=[];
            this.menuList3=[];
            this.sysMenu={};
            this.getMenuList();
            this.menu1Sort();
            this.menu2Sort();
        },
		getMenu: function(menuId){
			//加载菜单树
			$.get("../sys/menu/select?plat=" + this.plat, function(r){

				ztree = $.fn.zTree.init($("#menuTree"), setting, r.data);
				var node = ztree.getNodeByParam("menuId", vm.sysMenu.parentId);
				ztree.selectNode(node);
				
				vm.sysMenu.parentName = node.name;
			})
		},
        menu1Click: function(item){
            this.menuList2 = item.children;
            this.menuList3 = [item]

            $.get("../sys/menu/info/"+item.menuId, function(r){
                vm.sysMenu = r.data;
            });

            this.getMenu(item.menuId);
        },
        menu2Click: function(item){
            $.get("../sys/menu/info/"+item.menuId, function(r){
                vm.sysMenu = r.data;
            });

            this.getMenu(item.menuId);
        },
        menu1Sort: function(){
            $('#menu-list-1').nestable({
                group: 0,
                maxDepth:1
            }).on('change', menu2SortChance);

        },
        selectIcon: function(icon){

            if(vm.addView){
                vm.sysMenuAdd.icon = "fa fa-"+icon;
            }else{
                vm.sysMenu.icon = "fa fa-"+icon;
            }

            vm.dialogIconVisible = false;

        },
        menu1SortCancel: function(){
            self.location.reload();
        },
        menu2Sort: function(){
            $('#menu-list-2').nestable({
                group: 1,
                maxDepth:2
            }).on('change', menu2SortChance);
        },
        open:function () {
            this.showOpen = false;
            $('#menu-list-2').nestable('expandAll');
        },
        close:function () {
            this.showOpen = true;
            $('#menu-list-2').nestable('collapseAll');
        },
        menu2SortCancel: function(){
            $('#menu-list-2').unbind();
            var temp = this.menuList2;
            this.menuList2 = [];
            this.menuList2 = temp;
        },
		add: function(){
			vm.addView = true;
			vm.sysMenuAdd = {"type":0,"plat":1,"icon":"","parentName":""};
            vm.sysMenuAdd.plat= vm.plat;
            vm.sysMenuAdd.parentId = 0;
		},
        addMenu: function () {

            vm.sysMenuAdd.plat = vm.plat;
            vm.sysMenuAdd.orderNum = 1;

            var url = "../sys/menu/save";
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(vm.sysMenuAdd),
                success: function(r){
                    if(r.code === 0){
                        toastr.success('操作成功');
                        vm.showView=true;
                        vm.addView = false
                        vm.getMenuList();
                    }else{
                        toastr.error(r.msg);
                    }
                }
            });
        },
        saveMenu: function () {
            var url = vm.sysMenu.menuId == null ? "../sys/menu/save" : "../sys/menu/update";
            $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(vm.sysMenu),
                success: function(r){
                    if(r.code === 0){
                        toastr.success('操作成功');
                        vm.showView=true;
                        vm.getMenuList();
                    }else{
                        toastr.error(r.msg);
                    }
                }
            });
		},
		del: function (event) {
			var menuIds = getSelectedRows();
			if(menuIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: "../sys/menu/delete",
				    data: JSON.stringify(menuIds),
				    success: function(r){
				    	if(r.code === 0){
							alert('操作成功', function(index){
								vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function (event) {
			var url = vm.menu.menuId == null ? "../sys/menu/save" : "../sys/menu/update";
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.menu),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		menuTree: function(){
			layer.open({
				type: 1,
				offset: '50px',
				skin: 'layui-layer-molv',
				title: "选择菜单",
				area: ['300px', '450px'],
				shade: 0,
				shadeClose: false,
				content: jQuery("#menuLayer"),
				btn: ['确定', '取消'],
				btn1: function (index) {
					var node = ztree.getSelectedNodes();
					//选择上级菜单

                    if(vm.addView){
                        vm.sysMenuAdd.parentId = node[0].menuId;
                        vm.sysMenuAdd.parentName = node[0].name;
                    }else{
                        vm.sysMenu.parentId = node[0].menuId;
                        vm.sysMenu.parentName = node[0].name;
                    }
					
					layer.close(index);
	            }
			});
		},
		reload: function (event) {

		}
	}
});